package org.jeecg.modules.utils;

import lombok.SneakyThrows;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class TextToSound {
    public static final String API_KEY = "R5CjUIWvZOoQlrnaBC2As50A";
    public static final String SECRET_KEY = "bMOLMiKF2kGlADc1wxk9bqnoiRoTeqGk";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @SneakyThrows
    public static Boolean Tts(String text) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "tex="+text+"&cuid=1621423282132471810&ctp=1&lan=zh&vol=5&per=103&aue=6&tok="+getAccessToken());
        Request request = new Request.Builder()
                .url("https://tsn.baidu.com/text2audio?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "*/*")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        // 将音频文件保存到本地D盘根目录下
        File mp3File = new File("D:/output.wav");
        InputStream inputStream = response.body().byteStream();
        FileOutputStream mp3FileOutputStream = new FileOutputStream(mp3File);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            mp3FileOutputStream.write(buffer, 0, len);
        }
        mp3FileOutputStream.close();
        inputStream.close();
        return true;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    @SneakyThrows
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
